package com.eureka.journal.rocketmq;

import com.alibaba.fastjson.JSONObject;
import com.eureka.bclass.base.BaseLogEntity;
import com.eureka.bclass.constant.RocketMqTopicConstant;
import com.eureka.bclass.util.ConvertUtils;
import com.eureka.bclass.util.LoggerUtil;
import com.eureka.journal.entity.LogEntity;
import com.eureka.journal.service.LogService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * @Description: 系统日志监听器
 * @Author: lixing
 * @Date: 2021/6/14 10:17
 */
@Component
@RocketMQMessageListener(
        topic = RocketMqTopicConstant.LOG_TOPIC,                       // topic：和消费者发送的topic相同
        consumerGroup = "LogListener",             // group：不需要和生产者group相同 RocketMqTopicConstant.PROJECTNAME
        selectorExpression = RocketMqTopicConstant.LOG_TAG_API)        // tag: * 表示所有
public class LogListener implements RocketMQListener<BaseLogEntity> {

    @Resource
    private LogService logService;

    @Override
    public void onMessage(BaseLogEntity baseLogEntity) {
        if (null == baseLogEntity) {
            LoggerUtil.info("LogListener 入参为空");
        } else {
            boolean flag = true;
            try {
                LogEntity logEntity = ConvertUtils.convert(baseLogEntity, LogEntity.class);
                flag = logService.save(logEntity);
                if (!flag) {
                    LoggerUtil.info("LogListener 添加失败");
                }
            } catch (Exception e) {
                flag = false;
                LoggerUtil.info(MessageFormat.format("LogListener 添加出错: {0}", e.getMessage()));
            } finally {
                if (!flag) {
                    LoggerUtil.info(JSONObject.toJSONString(baseLogEntity));
                    LoggerUtil.info("");
                }
            }
        }
    }
}
